package com.example.handler;

import com.example.model.api.Result;
import com.example.model.api.ResultBuilder;
import com.example.utils.JSON;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import java.io.IOException;
import java.io.PrintWriter;

@Slf4j
public class SecurityAccessDeniedHandler implements AccessDeniedHandler {
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        response.setCharacterEncoding("utf-8");
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        response.setStatus(HttpStatus.FORBIDDEN.value()); // 403  401 404 400
        PrintWriter writer = response.getWriter();
        String message = accessDeniedException.getMessage();
        Result<String> result = ResultBuilder.<String>aResult().msg(message).code(HttpStatus.FORBIDDEN.value()).build();
        writer.print(JSON.stringify(result));
        writer.flush();
        writer.close();

    }
}
